package cn.myschool.web;

import cn.myschool.entity.Subject;
import cn.myschool.service.GradeService;
import cn.myschool.service.SubjectService;
import cn.myschool.util.StrUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author oldliu
 * @since 1.0
 */
@WebServlet("/subjectUpdate")
public class SubjectUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long id = StrUtil.toLong(req.getParameter("id"), -1L);
        Subject subject = SubjectService.ME.get(id);
        req.setAttribute("subject", subject);

        req.setAttribute("grades", GradeService.ME.findALL());

        req.getRequestDispatcher("/WEB-INF/jsp/subjectUpdate.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得修改值，然后保存
        request.setCharacterEncoding("utf-8");
        String subjectname = request.getParameter("subjectname");
        int classhour = Integer.parseInt(request.getParameter("classhour"));
        long gid = Long.parseLong(request.getParameter("gradeid"));

        long id = Long.parseLong(request.getParameter("id"));
        Subject sub = new Subject();
        sub.setId(id);
        sub.setSubjectname(subjectname);
        sub.setClasshour(classhour);
        sub.setGradeid(gid);
        int r = SubjectService.ME.update(sub);
        if (r > 0) {
            //表单重复提交：1）后退再提交 2）直接刷新
            //重定向，可以解决刷新一下，提交两次的问题
            //response.sendRedirect("subject.jsp");
            response.sendRedirect("subjectServlet");
            // request.getRequestDispatcher("subject.jsp").forward(request,response);
        } else {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("<script>alert('增加课程失败');window.history.back();</script>");
            // out.print("增加失败，可能课程名重复了！");
            //request.setAttribute("msg","增加失败，可能课程名重复了！");
            //request.getRequestDispatcher("/WEB-INF/jsp/subjectAdd.jsp").forward(request,response);
            //response.sendRedirect("subjectAdd.jsp");
        }
    }
}